/**
 * Created by baiguiren on 2/17/17.
 */

let _ = require('lodash');
let knex = require('../common/knex').knex;
let helper = require('../common/helper');
//let Promise = require('bluebird');
let eventproxy = require('eventproxy');

let getOrder = function (out_trade_no) {
  out_trade_no = _.trim(out_trade_no);
  return knex('tb_order').where('order_number', out_trade_no).first().then(function (order) {
    return new Promise(function (resolve, reject) {
      if (order) {
        resolve(order);
      } else {
        reject('订单不存在');
      }
    })
  });
};
exports.getOrder = getOrder;

//无法返回最后处理结果, 使用eventproxy触发调用者的事件
let dealOrder = function (pay_detail_info, ep) {
  if (pay_detail_info.out_trade_no === undefined) {
    return false;
  }
  getOrder(pay_detail_info.out_trade_no).then(function (order) {
    if (!order) {
      ep.emit('fail');
    } else {
      if (pay_detail_info) {
        pay_detail_info.create_time = helper.time();
        pay_detail_info.update_time = helper.time();
        let insert_ep = new eventproxy();
        let order_data = {};
        knex.transaction(function (trx) {
          insert_ep.on('insert_pay_detail', function (pay_detail_id) {
            order_data.pay_detail_id = pay_detail_id;
            order_data.pay_status = 1; //已支付
            order_data.status = 1; //订单状态改为等待发货
            order_data.update_time = helper.time();

            //更新商品销量信息, 支付成功后再更新商品销量
            knex('tb_order_goods').where('order_id', order.id).select().then(function (order_goods) {
              for (let order_good of order_goods) {
                //更新
                knex('tb_goods').where('id', order_good.goods_id).increment('sales', order_good.amount).then(function (affected_rows) {
                  if (order_good.amount !=0  && affected_rows != 1) {
                    trx.rollback();
                    ep.emit('fail');
                  }
                })
              }

              //更新订单
              knex('tb_order').where('id', order.id).update(order_data).then(function (affected_rows) {
                if (affected_rows == 1) {
                  trx.commit();
                  ep.emit('success');
                } else {
                  trx.rollback();
                  ep.emit('fail');
                }
              })
            });
          });
          if (pay_detail_info.appid !== undefined) {
            //微信支付详情
            knex('tb_wechatpay_detail').insert(pay_detail_info).then(function (pay_detail_id) {
              if (pay_detail_id) {
                order_data.pay_type = 1;
                insert_ep.emit('insert_pay_detail', pay_detail_id);
              } else {
                trx.rollback();
                ep.emit('fail');
              }
            });
          } else {
            //支付宝支付详情
            knex('tb_alipay_detail').insert(pay_detail_info).then(function (pay_detail_id) {
              if (pay_detail_id) {
                order_data.pay_type = 0;
                insert_ep.emit('insert_pay_detail', pay_detail_id);
              } else {
                trx.rollback();
                ep.emit('fail');
              }
            });
          }
        }).then(function (resp) {

        }).catch(function (error) {
          ep.emit('fail');
        })
      } else {
        ep.emit('fail');
      }
    }
  })
};
exports.dealOrder = dealOrder;

//过滤不需要保存的字段
let getAlipayDetail = function (pay_detail_info) {
  return {
    out_trade_no: pay_detail_info.pay_detail_info,
    subject: pay_detail_info.subject,
    payment_type: pay_detail_info.payment_type,
    trade_no: pay_detail_info.trade_no,
    trade_status: pay_detail_info.trade_status,
    seller_email: pay_detail_info.seller_email,
    buyer_email: pay_detail_info.buyer_email,
    total_fee: pay_detail_info.total_fee,
    gmt_create: pay_detail_info.gmt_create,
    gmt_payment: pay_detail_info.gmt_payment,
    create_time: helper.time(),
    update_time: helper.time()
  };
};
exports.getAlipayDetail = getAlipayDetail;

//生成的订单号格式20170220+6位时间戳+6位随机数
let newOrderNum = function () {
  let date = new Date();
  setTimeout(function () {}, 10);
  let date_str = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2);
  return date_str + Date.now().toString().slice(-6) + getRandom();
};
exports.newOrderNum = newOrderNum;

//生成6位随机数
let getRandom = function() {
  let random_str = Math.floor(Math.random() * 1000000).toString();
  if (random_str.length !== 6) {
    return getRandom();
  } else {
    return random_str;
  }
};
